﻿/*****************************************介绍*****************************************
 * 作者：Ywh
 * 创建时间：2024-04-09　01:38:32
 * 功能：复制动画控制器，并且为其重命名
**************************************************************************************/

using System.IO;
using UnityEditor;
using UnityEngine;

public class CopyAnimCtrlAndRename
{
    private const string DOUBLE = "_Double";
    private const string DUAL_WIELD = "_Dual_Double";

    [MenuItem("Assets/CustomTools/拷贝控制器")]
    private static void Copy()
    {
        string path = AssetDatabase.GetAssetPath(Selection.activeObject);
        bool isFloder = AssetDatabase.IsValidFolder(path);
        if (isFloder)
        {
            string[] assetGuids = AssetDatabase.FindAssets("t:AnimatorController", new[] { path });

            for (int i = 0; i < assetGuids.Length; i++)
            {
                string assetPath = AssetDatabase.GUIDToAssetPath(assetGuids[i]);
                string name = Path.GetFileNameWithoutExtension(assetPath);
                if (name.EndsWith(DOUBLE) || name.EndsWith(DUAL_WIELD)) continue;
                string doubleAssetPath = assetPath.Replace(name, $"{name}{DOUBLE}");
                string dualWieldAssetPath = assetPath.Replace(name, $"{name}{DUAL_WIELD}");
                OpetateAsset(assetPath, doubleAssetPath);
                //OpetateAsset(assetPath, dualWieldAssetPath);
            }
        }
    }

    private static void OpetateAsset(string assetPath, string newAssetPath)
    {
        // 删除
        if (AssetDatabase.LoadAssetAtPath<Object>(newAssetPath) != null)
            FileUtil.DeleteFileOrDirectory(newAssetPath);

        // 创建
        FileUtil.CopyFileOrDirectory(assetPath, newAssetPath);
        AssetDatabase.Refresh();

        // 改名
        Object doubleAsset = AssetDatabase.LoadAssetAtPath<Object>(newAssetPath);
        string fileName = Path.GetFileNameWithoutExtension(newAssetPath);
        if (doubleAsset.name != fileName)
        {
            doubleAsset.name = fileName;
            EditorUtility.SetDirty(doubleAsset);
            AssetDatabase.SaveAssets();
        }
    }
}